<?php

namespace App\Think;

use EasySwoole\Log\LoggerInterface;
use EasySwoole\EasySwoole\Config;

class Log implements LoggerInterface
{

    private $logDir;

    function __construct(string $logDir = null)
    {
        // if(empty($logDir)) $logDir = getcwd();
        $this->logDir = Config::getInstance()->getConf('LOG_DIR');
    }

    function log(?string $msg, int $logLevel = self::LOG_LEVEL_INFO, string $category = 'debug'):string
    {
        $date = date('Y-m-d H:i:s');
        $levelStr = $this->levelMap($logLevel);
        $fileDir = $this->logDir."/".date('Ymd');
        if (is_dir($fileDir) === FALSE){
		    @mkdir($fileDir);
		    @chmod($fileDir, 0777);
		} 
		$filePath = $fileDir."/log_{$category}.log";
        $str = "[{$date}][{$levelStr}][{$category}]: [{$msg}]\n";
        file_put_contents($filePath,"{$str}",FILE_APPEND|LOCK_EX);
        return $str;
    }

    function console(?string $msg, int $logLevel = self::LOG_LEVEL_INFO, string $category = 'console')
    {
        $date = date('Y-m-d H:i:s');
        $levelStr = $this->levelMap($logLevel);
        $temp = "[{$date}][{$levelStr}][{$category}]: [{$msg}]\n";
        fwrite(STDOUT,$temp);
    }

    private function levelMap(int $level)
    {
        switch ($level)
        {
            case self::LOG_LEVEL_INFO:
                return 'info';
            case self::LOG_LEVEL_NOTICE:
                return 'notice';
            case self::LOG_LEVEL_WARNING:
                return 'warning';
            case self::LOG_LEVEL_ERROR:
                return 'error';
            default:
                return 'unknown';
        }
    }
}